package com.sailmi.system.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.sailmi.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * UserImportListener
 *
 * @author Joffee
 */
public class UserImportListener extends AnalysisEventListener<UserExcel> {

	/**
	 * 默认每隔3000条存储数据库
	 */
	private int batchCount = 3000;
	/**
	 * 缓存的数据列表
	 */
	private List<UserExcel> list = new ArrayList<>();
	/**
	 * 用户service
	 */
	private final IUserService userService;

	public UserImportListener(IUserService userService) {
		this.userService = userService;
	}

	@Override
	public void invoke(UserExcel data, AnalysisContext context) {
		list.add(data);
		// 达到BATCH_COUNT，则调用importer方法入库，防止数据几万条数据在内存，容易OOM
		if (list.size() >= batchCount) {
			// 调用importer方法
			userService.importUser(list);
			// 存储完成清理list
			list.clear();
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		// 调用importer方法
		userService.importUser(list);
		// 存储完成清理list
		list.clear();
	}

	public int getBatchCount() {
		return batchCount;
	}

	public void setBatchCount(int batchCount) {
		this.batchCount = batchCount;
	}

	public List<UserExcel> getList() {
		return list;
	}

	public void setList(List<UserExcel> list) {
		this.list = list;
	}

	public IUserService getUserService() {
		return userService;
	}

}
